package com.billdowney.service.impl.system.notice.mail;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import com.billdowney.dao.system.notice.SystemNoticeDao;
import com.billdowney.entity.file.FileInfo;
import com.billdowney.entity.system.notice.SystemNotice;
import com.billdowney.entity.system.notice.SystemNoticeType;
import com.billdowney.exception.BizException;
import com.billdowney.service.impl.base.BaseServiceImpl;
import com.billdowney.service.interfaces.file.FileInfoService;
import com.billdowney.service.interfaces.system.notice.mail.MailService;
import com.billdowney.util.CommonUtil;
import com.billdowney.vo.mail.MailVO;

/**
 * 邮件服务接口实现
 * 
 * @author 超级小富翁 - BillDowney
 * @date 2019年3月23日 下午11:05:47
 */
@Service
public class MailServiceImpl extends BaseServiceImpl<SystemNoticeDao, SystemNotice, String> implements MailService {

	// 发送邮件服务
	@Autowired
	private JavaMailSender javaMailSender;
	// 发送者
	@Value("${spring.mail.username}")
	private String from;
	// 模板处理
	@Autowired
	private TemplateEngine templateEngine;
	// 文件服务
	@Autowired
	private FileInfoService fileInfoService;

	@Resource(type = SystemNoticeDao.class)
	@Override
	public void setDao(SystemNoticeDao dao) {
		super.dao = dao;
	}

	@Override
	public void sendSimpleMail(MailVO mailVO) {
		this.checkSendValue(mailVO);
		SimpleMailMessage message = new SimpleMailMessage();
		message.setFrom(from);
		message.setSubject(mailVO.getSubject());
		message.setText(mailVO.getContent());
		message.setTo(mailVO.getTo());
		javaMailSender.send(message);
		this.saveSystemNotice(mailVO, null);
	}

	@Override
	public void sendHtmlMail(MailVO mailVO) throws MessagingException, BizException {
		this.checkSendValue(mailVO);
		MimeMessage message = javaMailSender.createMimeMessage();
		MimeMessageHelper messageHelper = this.createMimeMessageHelper(mailVO, message);
		messageHelper.setFrom(from);
		messageHelper.setSubject(mailVO.getSubject());
		messageHelper.setText(mailVO.getContent(), true);
		messageHelper.setTo(mailVO.getTo());
		List<FileInfo> fileInfos = this.addAttachment(mailVO, messageHelper);
		javaMailSender.send(message);
		this.saveSystemNotice(mailVO, fileInfos);
	}

	@Override
	public void sendTemplateMail(MailVO mailVO) throws MessagingException, BizException {
		CommonUtil.isNotEmpty(mailVO.getTemplatePath(), new BizException(10504));
		Context context = new Context(LocaleContextHolder.getLocale());
		context.setVariables(mailVO.getTemplateParams());
		mailVO.setContent(templateEngine.process(mailVO.getTemplatePath(), context));
		this.sendHtmlMail(mailVO);
	}

	/**
	 * 检查必要的值是否为空
	 * 
	 * @param subject 主题
	 * @param content 发送内容
	 * @param to      接收的邮件列表
	 * @author: 超级小富翁 - BillDowney
	 * @date: 2019年3月24日 上午10:19:17
	 */
	private void checkSendValue(MailVO mailVO) {
		CommonUtil.isNotEmpty(mailVO.getSubject(), new BizException(10501));
		CommonUtil.isNotEmpty(mailVO.getContent(), new BizException(10502));
		CommonUtil.isNotEmpty(mailVO.getTo(), new BizException(10503));
	}

	/**
	 * 添加附件到邮件中
	 * 
	 * @param mailVO            {@link MailVO}
	 * @param mimeMessageHelper
	 * @return
	 * @author: 超级小富翁 - BillDowney
	 * @throws BizException       会发生找不到文件的异常
	 * @throws MessagingException MessagingException异常
	 * @date: 2019年3月26日 上午11:20:33
	 */
	private List<FileInfo> addAttachment(MailVO mailVO, MimeMessageHelper mimeMessageHelper)
			throws MessagingException, BizException {
		List<FileInfo> list = new ArrayList<FileInfo>();
		if (CommonUtil.isNotEmpty(mailVO.getFileIds())) {
			for (String fileId : mailVO.getFileIds()) {
				FileInfo fileInfo = fileInfoService.findFileInfoById(fileId);
				// 文件路径
				FileSystemResource file = new FileSystemResource(new File(fileInfo.getLocalFilePath()));
				mimeMessageHelper.addAttachment(fileInfo.getFileName(), file);
				list.add(fileInfo);
			}
		}
		return list;
	}

	/**
	 * 创建MimeMessageHelper对象
	 * 
	 * @param mailVO  {@link MailVO}
	 * @param message MimeMessage对象
	 * @return 根据是否需要附件的MimeMessageHelper对象
	 * @throws MessagingException
	 * @author: 超级小富翁 - BillDowney
	 * @date: 2019年3月26日 下午12:43:37
	 */
	private MimeMessageHelper createMimeMessageHelper(MailVO mailVO, MimeMessage mimeMessage)
			throws MessagingException {
		if (CommonUtil.isEmpty(mailVO.getFileIds())) {
			return new MimeMessageHelper(mimeMessage);
		} else {
			return new MimeMessageHelper(mimeMessage, true);
		}
	}

	/**
	 * 保存系统通知
	 * 
	 * @param mailVO    {@link MailVO}
	 * @param fileInfos 需要保存的文件列表
	 * @author: 超级小富翁 - BillDowney
	 * @date: 2019年3月28日 下午1:59:01
	 */
	private void saveSystemNotice(MailVO mailVO, List<FileInfo> fileInfos) {
		SystemNotice systemNotice = new SystemNotice();
		systemNotice.setSender(from);
		systemNotice.setSubject(mailVO.getSubject());
		systemNotice.setContent(mailVO.getContent());
		systemNotice.setFileInfos(fileInfos);
		systemNotice.setAddressee(mailVO.getTo());
		systemNotice.setNoticeType(SystemNoticeType.mail);
		dao.save(systemNotice);
	}

}
